<template>
  <v-app>
    <v-app-bar app color="primary" dark>
      <v-app-bar-nav-icon @click="drawer = !drawer"></v-app-bar-nav-icon>
      <v-toolbar-title>AI Health Guardian</v-toolbar-title>
      <v-spacer></v-spacer>

      <v-menu
          offset-y
          max-width="350px"
          :close-on-content-click="false"
      >
        <template v-slot:activator="{ props }">
          <v-btn icon v-bind="props" class="mr-2">
            <v-badge
                :model-value="alertStore.unreadAlerts > 0"
                :content="alertStore.unreadAlerts"
                color="red-darken-1"
            >
              <v-icon>mdi-bell-outline</v-icon>
            </v-badge>
          </v-btn>
        </template>

        <v-list lines="two" max-height="400" class="overflow-y-auto">
          <v-list-subheader class="font-weight-bold d-flex justify-space-between align-center">
            <span>健康提醒</span>
            <v-btn
                variant="text"
                size="small"
                color="primary"
                :disabled="alertStore.unreadAlerts === 0"
                @click="alertStore.markAllAsRead"
            >
              全部已读
            </v-btn>
          </v-list-subheader>

          <v-list-item v-if="alertStore.alerts.length === 0">
            <v-list-item-title class="text-grey text-center">
              {{ alertStore.isLoading ? '加载中...' : '暂无新消息' }}
            </v-list-item-title>
          </v-list-item>

          <template v-for="(alert, index) in alertStore.alerts" :key="alert.id">
            <v-list-item
                :title="alert.title"
                :subtitle="alert.subtitle"
                @click="alertStore.markAsRead(alert)" :class="{ 'new-alert': !alert.isRead }"
            >
              <template v-slot:prepend>
                <v-avatar :color="!alert.isRead ? 'primary' : 'grey-lighten-2'">
                  <v-icon color="white">{{ alert.icon || 'mdi-bell' }}</v-icon>
                </v-avatar>
              </template>
              <template v-slot:append>
                <v-icon v-if="!alert.isRead" color="blue" size="x-small">mdi-circle</v-icon>
              </template>
            </v-list-item>
            <v-divider v-if="index < alertStore.alerts.length - 1" class="my-1"></v-divider>
          </template>

          <v-list-item class="text-center">
            <v-btn variant="text" size="small" color="primary">查看全部</v-btn>
          </v-list-item>
        </v-list>
      </v-menu>

      <v-menu>
        <template v-slot:activator="{ props }">
          <v-btn icon v-bind="props">
            <v-avatar color="white" size="36">
              <span class="text-primary font-weight-bold">{{ userInitial }}</span>
            </v-avatar>
          </v-btn>
        </template>
        <v-list>
          <v-list-item @click="handleLogout">
            <v-list-item-title>退出登录</v-list-item-title>
          </v-list-item>
        </v-list>
      </v-menu>
    </v-app-bar>

    <v-navigation-drawer v-model="drawer" app>
      <v-list nav color="primary" class="main-nav-list">
        <v-list-item prepend-icon="mdi-view-dashboard" title="健康仪表盘" to="/dashboard"></v-list-item>
        <v-list-item prepend-icon="mdi-food-apple" title="饮食记录" to="/nutrition"></v-list-item>
        <v-list-item prepend-icon="mdi-dumbbell" title="运动计划" to="/workouts"></v-list-item>
        <v-list-item prepend-icon="mdi-weight-lifter" title="自由训练" to="/freeWorkout"></v-list-item>
        <v-list-item prepend-icon="mdi-clipboard-list-outline" title="我的模板" to="/my-templates"></v-list-item>
        <v-list-item prepend-icon="mdi-head-heart" title="心理陪伴" to="/chat"></v-list-item>
      </v-list>
    </v-navigation-drawer>

    <v-main class="bg-grey-lighten-3">
      <v-container fluid>
        <router-view></router-view>
      </v-container>
    </v-main>
    <v-snackbar
        v-model="notification.show"
        :timeout="notification.timeout"
        :color="notification.color"
        location="top"
        multi-line
    >
      {{ notification.text }}
      <template v-slot:actions>
        <v-btn variant="text" @click="notification.show = false">
          关闭
        </v-btn>
      </template>
    </v-snackbar>
    <v-btn
        icon="mdi-robot-happy-outline"
        color="deep-purple-accent-3"
        size="large"
        elevation="8"
        fab
        :style="fabStyle"
        @click="onFabClick"
        @mousedown="onFabDragStart"
    ></v-btn>
    <v-dialog v-model="chatDialog" max-width="600px" persistent>
      <v-card :style="dialogStyle">
        <v-card-title
            class="d-flex justify-space-between align-center pa-3 bg-primary"
            style="cursor: grab;"
            @mousedown="onDragStart"
        >
          <span class="text-white">AI 心理陪伴</span>
          <v-btn
              icon="mdi-close"
              variant="text"
              color="white"
              size="small"
              @click="chatDialog = false"
          ></v-btn>
        </v-card-title>
        <AiCompanionChat v-if="chatDialog" :is-in-dialog="true"/>
      </v-card>
    </v-dialog>
  </v-app>
</template>

<script setup>
import {ref, computed, reactive, watch, onMounted} from 'vue';
import {useRouter} from 'vue-router';
import {useUserStore} from '@/stores/user';
import {useNotificationStore} from '@/stores/notification';
import {removeToken} from '@/utils/Storage';
import Request from '@/utils/Request';
import AiCompanionChat from "@/components/AiCompanionChat.vue";

// 【!! V7 动态升级：导入并使用 Alert Store !!】
import {useAlertStore} from '@/stores/alertStore'; // 确保路径正确

// (原始 Refs 保持不变)
const drawer = ref(true);
const router = useRouter();
const userStore = useUserStore();
const notification = useNotificationStore();
const chatDialog = ref(false);
const userInitial = computed(() => userStore.userProfile?.firstName?.charAt(0).toUpperCase() || 'U');

// 【!! V7 动态升级：实例化 Store !!】
const alertStore = useAlertStore();

// (handleLogout 保持不变)
const handleLogout = async () => {
  if (!window.confirm('您确定要退出登录吗？')) {
    return;
  }
  try {
    await Request.post('/auth/logout');
  } catch (err) {
    console.error("调用登出接口失败 (不影响前端登出):", err);
  } finally {
    removeToken();
    userStore.clearUserProfile();
    notification.success('您已成功退出登录');
    router.push({name: 'Login'});
  }
};

// --- (对话框拖动逻辑保持不变) ---
const isDragging = ref(false);
const dragStart = reactive({x: 0, y: 0, dialogX: 0, dialogY: 0});
const dialogPosition = reactive({x: 0, y: 0});
const dialogStyle = computed(() => ({
  transform: `translate(${dialogPosition.x}px, ${dialogPosition.y}px)`,
  cursor: isDragging.value ? 'grabbing' : 'grab',
}));
const onDragStart = (event) => {
  if (event.button !== 0) return;
  isDragging.value = true;
  dragStart.x = event.clientX;
  dragStart.y = event.clientY;
  dragStart.dialogX = dialogPosition.x;
  dragStart.dialogY = dialogPosition.y;
  window.addEventListener('mousemove', onDragMove);
  window.addEventListener('mouseup', onDragEnd);
  event.preventDefault();
};
const onDragMove = (event) => {
  if (!isDragging.value) return;
  const dx = event.clientX - dragStart.x;
  const dy = event.clientY - dragStart.y;
  dialogPosition.x = dragStart.dialogX + dx;
  dialogPosition.y = dragStart.dialogY + dy;
};
const onDragEnd = () => {
  isDragging.value = false;
  window.removeEventListener('mousemove', onDragMove);
  window.removeEventListener('mouseup', onDragEnd);
};
watch(chatDialog, (isOpen) => {
  if (!isOpen) {
    setTimeout(() => {
      dialogPosition.x = 0;
      dialogPosition.y = 0;
    }, 200);
  }
});
// --- (对话框拖动逻辑结束) ---

// --- (FAB 拖动逻辑保持不变) ---
const fabSize = 56;
const fabPadding = 24;
const fabX = ref(0);
const fabY = ref(0);
const isFabDragging = ref(false);
const hasFabMoved = ref(false);
const fabDragStart = reactive({x: 0, y: 0, fabX: 0, fabY: 0});
const fabStyle = computed(() => ({
  position: 'fixed',
  left: `${fabX.value}px`,
  top: `${fabY.value}px`,
  zIndex: 999,
  cursor: isFabDragging.value ? 'grabbing' : 'grab',
}));

// 【!! V7 动态升级：在 onMounted 中触发第一次获取 !!】
onMounted(() => {
  // 1. FAB 悬浮球的位置 (保持不变)
  fabX.value = window.innerWidth - fabSize - fabPadding;
  fabY.value = window.innerHeight - fabSize - fabPadding;

  // 2. (新增) 获取健康提醒
  alertStore.init();
});

const onFabDragStart = (event) => {
  if (event.button !== 0) return;
  isFabDragging.value = true;
  hasFabMoved.value = false;
  fabDragStart.x = event.clientX;
  fabDragStart.y = event.clientY;
  fabDragStart.fabX = fabX.value;
  fabDragStart.fabY = fabY.value;
  window.addEventListener('mousemove', onFabDragMove);
  window.addEventListener('mouseup', onFabDragEnd);
  event.preventDefault();
};
const onFabDragMove = (event) => {
  if (!isFabDragging.value) return;
  const dx = event.clientX - fabDragStart.x;
  const dy = event.clientY - fabDragStart.y;
  if (Math.abs(dx) > 5 || Math.abs(dy) > 5) {
    hasFabMoved.value = true;
  }
  let newX = fabDragStart.fabX + dx;
  let newY = fabDragStart.fabY + dy;
  const minX = fabPadding;
  const minY = fabPadding;
  const maxX = window.innerWidth - fabSize - fabPadding;
  const maxY = window.innerHeight - fabSize - fabPadding;
  newX = Math.max(minX, Math.min(newX, maxX));
  newY = Math.max(minY, Math.min(newY, maxY));
  fabX.value = newX;
  fabY.value = newY;
};
const onFabDragEnd = () => {
  isFabDragging.value = false;
  window.removeEventListener('mousemove', onFabDragMove);
  window.removeEventListener('mouseup', onFabDragEnd);
};
const onFabClick = () => {
  if (!hasFabMoved.value) {
    chatDialog.value = true;
  }
};
// --- (FAB 拖动逻辑结束) ---
</script>

<style>
.main-nav-list .v-list-item--active .v-list-item-title {
  font-weight: 700 !important;
}

.new-alert .v-list-item-title {
  font-weight: 500;
}
</style>